package backends

import (
	"log"

	"gitee.com/chenrh/finego/app"
	"gitee.com/chenrh/finego/backends/models"
	"gitee.com/chenrh/gotoolkit/hash"
	"gorm.io/gorm"
)

// AutoMigrate 注册 Model 类
func AutoMigrate() {
	db := app.GetDB()

	db.AutoMigrate(&models.PUB_USER{}, &models.PUB_USER_LOG{})

	db.AutoMigrate(&models.STOCK_INFO{}, &models.STK_SELF_SELECT{}, &models.STOCK_COMMENTS{})
	db.AutoMigrate(&models.STK_CALENDAR_EVENTS{})
	db.AutoMigrate(&models.STK_GROUP{}, &models.STK_GROUP_MEMBER{})
	db.AutoMigrate(&models.STK_MESSAGE{})

	db.AutoMigrate(&models.FUND_INFO{}, &models.FUND_STOCK{})

	db.AutoMigrate(&models.WX_AUTHORIZE{})

	if app.AppConfig.AutoCreateAdminAccount == "y" {
		autoCreateAdminAccount(db)
	}
}

// autoCreateAdminAccount 1. 用户表没有管理员数据时，建立管理员帐号
func autoCreateAdminAccount(db *gorm.DB) {
	var user models.PUB_USER
	db.Where("user_code = ?", "admin").First(&user)

	if user.UserId == 0 {
		salt := hash.RandomString(6)
		pass := "a,1234"
		passEncode := hash.Md5Encode(pass + salt)
		user = models.PUB_USER{
			UserId:    -1,
			UserCode:  "admin",
			NickName:  "管理员",
			UserPhone: "13023621609",
			Email:     "v1108@qq.com",
			LoginPass: passEncode,
			LoginSalt: salt,
		}
		user.CreatedBy = "[程序自动建立]"
		user.UpdatedBy = "[程序自动建立]"
		db.Create(&user)
		log.Printf("已自动为您创建管理员账号：%s 密码 %s", user.UserCode, pass)
	}
}
